package com.demo.xj_plane.controller;

import com.demo.xj_plane.common.utils.*;
import com.demo.xj_plane.entity.XjLiveSaEntity;
import com.demo.xj_plane.entity.XjSelfObsEntity;
import com.demo.xj_plane.entity.XjThresholdDefaultEntity;
import com.demo.xj_plane.entity.XjThresholdEntity;
import com.demo.xj_plane.service.XjLiveSaService;
import com.demo.xj_plane.service.XjSelfObsService;
import com.demo.xj_plane.service.XjThresholdDefaultService;
import com.demo.xj_plane.service.XjThresholdService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/fourGrids")
@Api(value = "四字格阈值接口", tags = {"获取四字格阈值相关数据"})
@Slf4j
public class FourGridsThresholdController extends BaseController {

    @Autowired
    private XjThresholdService xjThresholdService;

    @Autowired
    private XjThresholdDefaultService xjThresholdDefaultService;

    @Autowired
    private XjSelfObsService xjSelfObsService;

    @Autowired
    private XjLiveSaService xjLiveSaService;

    /**
     * 计算侧风和顺逆风
     *
     * @param wind2d 风向（度数）
     * @param wind2f 风速（单位：米/秒）
     * @param way    跑道方向（度数）
     * @return 包含侧风和顺风的字符串数组 [侧风, 顺风]
     */
    public static double[] calculateCrosswindAndDownwind(int wind2d, double wind2f, int way) {
        // 计算风向与跑道方向的角度差
        //double rad = Math.abs(wind2d - way) / 180.0 * Math.PI;
        double rad = Math.abs(wind2d - way * 10) / 180.0 * Math.PI;


        // 计算侧风（crosswind）和顺风（downwind）
        double crosswind = Math.abs(wind2f * Math.sin(rad));
        double downwind = Math.abs(wind2f * Math.cos(rad));

        // 保留两位小数
        crosswind = Math.round(crosswind * 100.0) / 100.0;
        downwind = Math.round(downwind * 100.0) / 100.0;

        // 返回侧风和顺风的 double 数组
        return new double[]{crosswind, downwind};
    }

    @GetMapping(value = "/getThreshold")
    @ApiOperation(value = "1、获取当前机场的一些阈值", notes = "风速，能见度，云底高")
    public ResponseJson getAwosLine() {
        // 新疆所有机场
        List<String> ccccLst = GlobalConstant.allXjPlaneList;
        // 返回结果
        Map<String, Object> allMap = new HashMap<>();
        for(String cccc : ccccLst){
            // 返回最终结果
            Map<String,Map<String, Object>> resultMap = new HashMap<>();
            allMap.put(cccc, resultMap);
            // 四方格数据
            Map<String, Object> dataMap = new HashMap<>();
            // 四方格颜色
            Map<String, Object> colorMap = new HashMap<>();
            // SP报文内容
            Map<String, Object> spContentMap = new HashMap<>();
            // 获取当前世界时半小时前时间
            String curTimeAgo = DateUtil.getCurrentTimeUtcAgo();
            // 查找半小时内的SP报文
            String spContent = xjLiveSaService.selectContentLast30Min(cccc, "SP", curTimeAgo);
            spContentMap.put("context", spContent);
            resultMap.put("spContent", spContentMap);
            // 默认值为空
            colorMap.put("WINDColor","");
            colorMap.put("YDGColor","");
            colorMap.put("TQColor","");
            colorMap.put("NJDColor","");

            // 获取机场最小跑道
            String pointCode = GlobalConstant.allXjPlaneFirstPcMap.get(cccc);
            // 查询阈值数据
            XjThresholdEntity xjtr = xjThresholdService.selectThreshold(cccc, pointCode);
            if (xjtr == null) {
                // 没有阈值直接跳过
                continue;
            }

            // 查询并计算风速（自观）
            XjSelfObsEntity obs = xjSelfObsService.selectFourGridsData(cccc, pointCode);
            if (obs != null) {
                // 自然风
                dataMap.put("ZRF", obs.getWindF2());
                // 能见度
                dataMap.put("NJD_ZG", obs.getMor1A());
                // 云底高
                dataMap.put("YDG", obs.getCldHh());
                // 云底高颜色判断（只取YDG的颜色）
                String cloudHeightColor = getCloudHeightColor(obs.getCldHh(), xjtr);
                colorMap.put("YDGColor", cloudHeightColor);
                // 如果不是mid，则跑道角度取POINT_CODE
                String way = obs.getPointCode();
                if (obs.getPointCode().equals("MID")) {
                    way = obs.getRno().split("/")[1];
                }
                // 计算侧风，顺逆风
                double[] winds = calculateCrosswindAndDownwind(obs.getWindD2(), obs.getWindF2(), Integer.parseInt(way));
                // 侧风
                dataMap.put("CF", winds[0]);
                // 顺逆风
                dataMap.put("SNF", winds[1]);
                colorMap.put("WINDColor", getWindColor((Double) dataMap.get("ZRF"), (Double) dataMap.get("ZRF"), (Double) dataMap.get("ZRF"), xjtr));
            }

            // sasp报文数据
            XjLiveSaEntity sa = xjLiveSaService.selectFourGridsData(cccc);
            if (sa != null) {
                // 天气现象
                dataMap.put("TQXX", sa.getEvent());
                colorMap.put("TQColor", "GREEN");
                if(StringUtils.isNotBlank(sa.getEvent())){
                    colorMap.put("TQColor", "RED");
                }
                // 能见度
                dataMap.put("NJD_SA", sa.getVisibility());

                // 能见度颜色判断（NJD_ZG 和 NJD_SA）
                if(obs == null){
                    String visibilitySAColor = getColorNjd(sa.getVisibility(), xjtr.getVisibilityThLevel1(), xjtr.getVisibilityThLevel2(), xjtr.getVisibilityThLevel3());
                    colorMap.put("NJDColor", visibilitySAColor);
                } else {
                    String visibilityColor = getVisibilityColor(obs.getMor1A(), sa.getVisibility(), xjtr);
                    colorMap.put("NJDColor", visibilityColor);
                }
            }
            // 封装四方格颜色...
            resultMap.put("dataMap",dataMap);
            resultMap.put("colorMap",colorMap);

        }

        return ResponseJson.success(allMap);
    }

    // 封装四方格的颜色
    private String getWindColor(double crossWind, double tailWind, double naturalWind, XjThresholdEntity thresholds) {
        String maxColor = "GREEN"; // 默认绿色

        // 比较侧风、顺风、自然风的颜色，取最大级别
        String crossWindColor = getColor(crossWind, thresholds.getCrossWindLevel1(), thresholds.getCrossWindLevel2(), thresholds.getCrossWindLevel3());
        String tailWindColor = getColor(tailWind, thresholds.getTailWindLevel1(), thresholds.getTailWindLevel2(), thresholds.getTailWindLevel3());
        String naturalWindColor = getColor(naturalWind, thresholds.getNaturalWindLevel1(), thresholds.getNaturalWindLevel2(), thresholds.getNaturalWindLevel3());

        // 比较三者颜色，取最高级别
        maxColor = getMaxColor(maxColor, crossWindColor, tailWindColor, naturalWindColor);
        return maxColor;
    }

    /**
     * 封装能见度颜色，包含自观和sa报文两个，去最大值
     * @param visibility1
     * @param visibility2
     * @param thresholds
     * @return
     */
    private String getVisibilityColor(int visibility1, int visibility2, XjThresholdEntity thresholds) {
        String maxColor = "GREEN"; // 默认绿色

        // 能见度的颜色判断，比较NJD_ZG和NJD_SA
        String visibilityZGColor = getColorNjd(visibility1, thresholds.getVisibilityThLevel1(), thresholds.getVisibilityThLevel2(), thresholds.getVisibilityThLevel3());
        String visibilitySAColor = getColorNjd(visibility2, thresholds.getVisibilityThLevel1(), thresholds.getVisibilityThLevel2(), thresholds.getVisibilityThLevel3());

        // 取两者中的最大颜色
        maxColor = getMaxColor(maxColor, visibilityZGColor, visibilitySAColor);
        return maxColor;
    }

    // 封装云底高颜色
    private String getCloudHeightColor(int cloudHeight, XjThresholdEntity thresholds) {
        return getColor(cloudHeight, thresholds.getCldhlThLevel1(), thresholds.getCldhlThLevel2(), thresholds.getCldhlThLevel3());
    }

    /**
     * 判断四方格颜色（double）
     * @param value
     * @param level1
     * @param level2
     * @param level3
     * @return
     */
    private String getColor(double value, double level1, double level2, double level3) {
        if (value >= level3) {
            return "RED";
        } else if (value >= level2) {
            return "YELLOW";
        } else if (value >= level1) {
            return "GREEN";
        } else {
            return "GREEN"; // 默认正常绿色
        }
    }

    /**
     * 能见度越小，则越红
     * @param value
     * @param level1
     * @param level2
     * @param level3
     * @return
     */
    private String getColorNjd(double value, double level1, double level2, double level3) {
        if (value <= level3) {
            return "RED";   // 值越小，颜色越红
        } else if (value <= level2) {
            return "YELLOW"; // 介于level3和level2之间，返回黄色
        } else if (value <= level1) {
            return "GREEN";  // 介于level2和level1之间，返回绿色
        } else {
            return "GREEN";  // 默认绿色
        }
    }


    /**
     * 判断四方格颜色（int）
     * @param value
     * @param level1
     * @param level2
     * @param level3
     * @return
     */
    private String getColor(int value, int level1, int level2, int level3) {
        if (value >= level3) {
            return "RED";
        } else if (value >= level2) {
            return "YELLOW";
        } else if (value >= level1) {
            return "GREEN";
        } else {
            return "GREEN"; // 默认正常绿色
        }
    }

    /**
     * 比较最大颜色
     * @param colors
     * @return
     */
    private String getMaxColor(String... colors) {
        String maxColor = "GREEN";
        for (String color : colors) {
            if ("RED".equals(color)) {
                return "RED";
            } else if ("YELLOW".equals(color) && !"RED".equals(maxColor)) {
                maxColor = "YELLOW";
            }
        }
        return maxColor;
    }


    /**
     * 查看机场阈值信息
     * @param pagerInfo
     * @return
     */
    @PostMapping(value = "/page")
    @ApiOperation(value = "2、分页查询", notes = "务必提交json格式")
    public ResponseJson selectPage(@RequestBody PagerInfo pagerInfo) {
        // 将分页信息从请求体中提取为查询条件
        Map<String, Object> params = pageInfoToMap(pagerInfo);
        // 查询机场阈值分页总数
        int total = xjThresholdService.pageCount(params);
        // 查询机场阈值分页数据
        List<XjThresholdEntity> list = xjThresholdService.pageList(params);
        // 返回包含机场阈值列表和总数的响应体
        return ResponseJson.success(total, list);
    }

    /**
     * 新增机场阈值
     * @param xjThresholdEntity
     * @return
     */
    @PostMapping(value = "/insert")
    @ApiOperation(value = "3、新增", notes = "务必提交json格式")
    public ResponseJson insert(@RequestBody @Validated XjThresholdEntity xjThresholdEntity){
        // 判断是否已经存在
        XjThresholdEntity xjExist = xjThresholdService.selectThreshold(xjThresholdEntity.getCccc(), xjThresholdEntity.getPointCode());
        if (xjExist != null) {
            ResponseJson.fail("该机场跑道阈值信息已添加，不要重复添加...");
        }
        xjThresholdEntity.setIntm(DateUtil.getCurrentTime());
        // 新增机场阈值数据
        boolean isOk = xjThresholdService.save(xjThresholdEntity);
        if (isOk) {
            return ResponseJson.success();
        } else {
            return ResponseJson.fail("新增机场阈值信息失败");
        }
    }

    /**
     * 修改&恢复默认值
     * @param xjThresholdEntity
     * @return
     */
    @PostMapping(value = "/update")
    @ApiOperation(value = "4、修改", notes = "务必提交json格式")
    public ResponseJson update(@RequestBody @Validated XjThresholdEntity xjThresholdEntity, @RequestParam Boolean isDefault) {
        // 判断是修改还是恢复默认值
        if(isDefault){
            XjThresholdDefaultEntity xjDefault = xjThresholdDefaultService.selectThresholdDefault(xjThresholdEntity.getCccc(), xjThresholdEntity.getPointCode());
            // 使用 BeanUtils 复制属性
            BeanUtils.copyProperties(xjDefault, xjThresholdEntity);
        }
        // 先删后增
        if(StringUtils.isBlank(xjThresholdEntity.getCccc()) || StringUtils.isBlank(xjThresholdEntity.getPointCode())){
            return ResponseJson.fail("机场代码和跑道号不能为空");
        }
        xjThresholdService.deleteThreshold(xjThresholdEntity.getCccc(), xjThresholdEntity.getPointCode());
        // 修改时间 intm
        xjThresholdEntity.setIntm(DateUtil.getCurrentTime());
        // 后增
        boolean isOk = xjThresholdService.save(xjThresholdEntity);
        if (isOk) {
            return ResponseJson.success();
        } else {
            return ResponseJson.fail("修改机场阈值信息失败");
        }
    }

    @GetMapping(value = "/delete")
    @ApiOperation(value = "6、通过zbrId删除数据")
    public ResponseJson delSds(@RequestParam("cccc") String cccc, @RequestParam("pointCode") String pointCode) {
        // 根据id删除所选值班人员信息，以及排班信息
        Boolean isOk = xjThresholdService.deleteThreshold(cccc, pointCode);
        // 根据删除结果返回相应的 ResponseJson 对象
        if (isOk) {
            return ResponseJson.success();
        } else {
            return ResponseJson.fail("删除机场阈值信息失败");
        }
    }


}
